<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\model\FlightModel;
use app\admin\model\FrontUserModel;
use app\admin\model\BalanceModel;
use  think\Cache;

class Data extends Base
{
    // 备份首页列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $where = [];
            if (!empty($param['searchText'])) {
                $where['xl_front_user.username'] = ['like', '%' . $param['searchText'] . '%'];
            }
            $user = new BalanceModel();
            $selectResult = $user->getUsersByWhere($where, $offset, $limit);

            $status = config('balance_types');

            // 拼装参数
            foreach($selectResult as $key=>$vo){

                $selectResult[$key]['ctime'] = date('Y-m-d H:i:s', $vo['ctime']);
                $selectResult[$key]['types'] = $status[$vo['types']];
                if( 1 == $vo['id'] ){
                    $selectResult[$key]['operate'] = '';
                    continue;
                }
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id']));
            }
            $return['total'] = $user->getAllUsers($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        return $this->fetch();
    }
    /*
     *  导入execl文件
     */
    public function importExecl()
    {
        if (!request()->isPost()) {
            $this->error('400 请上传文件');
        }
        $file = request()->file('excel');
        if (empty($file)) {
            $this->error('400 请上传文件');
        }
        vendor('PHPExcel.PHPExcel');
        $PHPExcel = new \PHPExcel();
        $info = $file->validate(['size'=>15678,'ext'=>'xlsx,xls,csv'])->move(ROOT_PATH . 'public' . DS . 'upload' .DS. 'excel');
        if (empty($info)) {
            $this->error('400 文件上传失败');
        }
        $exclePath = $info->getSaveName();
        $file_name = ROOT_PATH . 'public' . DS . 'upload' .DS. 'excel' . DS . $exclePath;
        $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
        $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');
        $excel_array = $obj_PHPExcel->getsheet(0)->toArray();
        unset($excel_array[0]);
        $flight = new FlightModel();
        $arr = [];
        foreach ($excel_array as $v) {
            if ($v[0]) {
                $data['trip'] = $v[0];
                $data['return_trip'] = $v[1];
                $data['trip_time'] = strtotime($v[2]);
                $data['rt_time'] = strtotime($v[3]);
                $data['tr_flight'] = $v[4];
                $data['retr_flight'] = $v[5];
                $data['tto_time'] = strtotime(date('Y-m-d ',$data['trip_time']) . $v[6]);
                $data['rto_time'] = strtotime(date('Y-m-d ',$data['trip_time']) . $v[7]);
                $data['round_days'] = $v[8];
                $data['price'] = $v[9];
                $data['stock'] = $v[10];
                $data['create_time'] = time();
                array_push($arr, $data);
            }
        }
        $msg = $flight->insertAll($arr);
        if ($msg) {
            $this->success('成功');
        } else {
            $this->error('400 保存数据失败');
        }
    }

    // 备份数据
    public function importData()
    {
        set_time_limit(0);
        $table = input('param.table');

        $sqlStr = "SET FOREIGN_KEY_CHECKS=0;\r\n";
        $sqlStr .= "DROP TABLE IF EXISTS `$table`;\r\n";
        $create = db()->query('show create table ' . $table);
        $sqlStr .= $create['0']['Create Table'] . ";\r\n";
        $sqlStr .= "\r\n";

        $result = db()->query('select * from ' . $table);
        foreach($result as $key=>$vo){
            $keys = array_keys($vo);
            $keys = array_map('addslashes', $keys);
            $keys = join('`,`', $keys);
            $keys = "`" . $keys . "`";
            $vals = array_values($vo);
            $vals = array_map('addslashes', $vals);
            $vals = join("','", $vals);
            $vals = "'" . $vals . "'";
            $sqlStr .= "insert into `$table`($keys) values($vals);\r\n";
        }

        $filename = config('back_path') . $table . ".sql";
        $fp = fopen($filename, 'w');
        fputs($fp, $sqlStr);
        fclose($fp);

        return json(['code' => 1, 'data' => '', 'msg' => 'success']);
    }

    // 还原数据
    public function backData()
    {
        set_time_limit(0);
        $table = input('param.table');

        if(!file_exists(config('back_path') . $table . ".sql")){
            return json(['code' => -1, 'data' => '', 'msg' => '备份数据不存在!']);
        }

        $sqls = analysisSql(config('back_path') . $table . ".sql");
        foreach($sqls as $key=>$sql){
            db()->query($sql);
        }
        return json(['code' => 1, 'data' => '', 'msg' => 'success']);
    }

    /**
     * 拼装操作按钮
     * @param $table
     * @return array
     */
    private function makeButton($table)
    {
        return [
            '备份' => [
                'auth' => 'data/importdata',
                'href' => "javascript:importData('" .$table ."')",
                'btnStyle' => 'primary',
                'icon' => 'fa fa-tasks'
            ],
            '还原' => [
                'auth' => 'data/backdata',
                'href' => "javascript:backData('" .$table ."')",
                'btnStyle' => 'info',
                'icon' => 'fa fa-retweet'
            ]
        ];
    }

    public function edit()
    {
        $id = input('param.id');
        $flight = new FlightModel();
        if (request()->isPost()) {
            $param = input('post.');
            $flight->editApply($param, ['id'=>$param['id']]);
            $this->success('操作成功','/admin/data/edit?id='.$param['id'], '' , 1);
        }
        $data = $flight->getOneApply($id);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function dataDel()
    {
        $id = input('param.id');
        $flight = new FlightModel();
        $flag = $flight->delApply($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    public function dataDelArr()
    {
        $id = input('param.');
        $ids = $id['ids'];
        $flight = new FlightModel();
        $flag = $flight->delApply($ids);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }
}
